﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Caliburn.Micro;
using Wulong.Phone.Qiushi.i18n;
using Wulong.Phone.Qiushi.Models;
using Wulong.Phone.Utils;

namespace Wulong.Phone.Qiushi.ViewModels
{
    public enum LangSupported
    {
        Auto,
        Chinese,
        English
    }

    public enum QiushiSectionEnum
    {
        Latest,
        EightHours,
        TwentyFourHours,
        PicStory
    }

    public class MainViewModel : BusyIndicatorViewModelBase 
    {        

        public MainViewModel(
                            INavigationService navigationService,
                            IEventAggregator events
                            )
        {            
            _navigationService = navigationService;
            _events = events;           
            InitStates();
        }

        private void InitStates()
        {
            _picstoryList = new ObservableCollection<QiushiItem>();
            BackgroundImage = new ImageBrush{ImageSource = new BitmapImage(DefaultPlaceholder)};
            
            int saveLang;
            _settingLangSelectedIndex = (AppSettings.TryGetSetting("Lang", out saveLang)
                                             ? saveLang
                                             : 0);
            NaviSelectedIndex = -1;
            SelectedItem = null;
        }

        private int _naviSelectedIndex;

        public int NaviSelectedIndex
        {
            get { return _naviSelectedIndex; }
            set
            {
                if (_naviSelectedIndex == value)
                    return;
                _naviSelectedIndex = value;
                NotifyOfPropertyChange(() => NaviSelectedIndex);
            }
        }

        public void NavigateToQiushiListView()
        {
            switch ((QiushiSectionEnum)NaviSelectedIndex)
            {
                case QiushiSectionEnum.Latest:
                    _navigationService.UriFor<QiushiListViewModel>()
                        .WithParam(x => x.DisplayName, AppResources.VM_QiushiSection_Latest)
                        .WithParam(x => x.Section, "l")
                        .Navigate();
                    break;
                case QiushiSectionEnum.EightHours:
                    _navigationService.UriFor<QiushiListViewModel>()
                        .WithParam(x => x.DisplayName, AppResources.VM_QiushiSection_8hrs)
                        .WithParam(x => x.Section, "8")
                        .Navigate();
                    break;
                case QiushiSectionEnum.TwentyFourHours:
                    _navigationService.UriFor<QiushiListViewModel>()
                        .WithParam(x => x.DisplayName, AppResources.VM_QiushiSection_24hrs)
                        .WithParam(x => x.Section, "d")
                        .Navigate();
                    break;
                case QiushiSectionEnum.PicStory:
                    _navigationService.UriFor<QiushiListViewModel>()
                        .WithParam(x => x.DisplayName, AppResources.VM_QiushiSection_Picstory)
                        .WithParam(x => x.Section, "p")
                        .Navigate();
                    break;
            }
        }
        private int _settingLangSelectedIndex;
        public int SettingLangSelectedIndex
        {
            get { return _settingLangSelectedIndex; }
            set
            {
                _settingLangSelectedIndex = value;
                NotifyOfPropertyChange(() => SettingLangSelectedIndex);
            }
        }

        public void SaveLangSetting()
        {
            AppSettings.StoreSetting("Lang", SettingLangSelectedIndex);
        }

        private static readonly Uri DefaultPlaceholder = new Uri("/images/PanoBackground.jpg", UriKind.Relative);
        
        public ImageBrush BackgroundImage { get; private set; }

        protected override void OnInitialize()
        {            
            
        }

        private QiushiItem _selectedItem;

        public QiushiItem SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                if (_selectedItem == value)
                    return;
                _selectedItem = value;
                NotifyOfPropertyChange(() => SelectedItem);
            }
        }

        public void ViewPicture(QiushiItem item)
        {
            _navigationService.UriFor<PicViewModel>()
                .WithParam(x => x.ImageUrl, item.ImageUrl)
                .Navigate();
        }

        private static void DoAfterException(Exception ex)
        {
            MessageBox.Show(AppResources.Ex_Network_Down_Message + "\r\n" + ex.Message,
                            AppResources.Ex_Error_Title,
                            MessageBoxButton.OK);
        }

        private void DoAfterCompleted()
        {
            CountOfItemsUpdated = 0;
        }

        private bool _canViewPicture;

        public bool CanViewPicture
        {
            get { return _canViewPicture; }
            set
            {
                if (_canViewPicture == value)
                    return;
                _canViewPicture = value;
                NotifyOfPropertyChange(() => CanViewPicture);
            }
        }
        
        public ObservableCollection<QiushiItem> _picstoryList;

        public IEnumerable<QiushiItem> PicstoryList
        {
            get { return _picstoryList; }
        }

        protected override void OnViewReady(object view)
        {
            base.OnViewReady(view);
            if(_picstoryList.Count()==0)
                LoadPictures();
        }

        public virtual IEnumerable<IResult> OnViewReady()
        {
            yield break;
        }

        public int CountOfItemsUpdated { get; set; }

        private void LoadPictures()
        {
            if(IsBusy)
                return;
            IsBusy = true;
            CanViewPicture = false;
            CanRefreshPicList = false;
            _subject= QiushiMapper.GetObservableItems("p", 10)
                .Where(item=> !string.IsNullOrWhiteSpace(item.ImageUrl))
                .ObserveOnDispatcher()
                .Finally(() => 
                                { 
                                    IsBusy = false;
                                    CanViewPicture = true;
                                    CanRefreshPicList = true;
                                })
                .Subscribe(item =>
                               {
                                   if (IsContained(item.Id)) return;
                                   CountOfItemsUpdated += 1;
                                   _picstoryList.Insert(CountOfItemsUpdated - 1, item);
                               },
                           DoAfterException,
                           DoAfterCompleted);
        }

        private bool _canRefreshPicList;

        public bool CanRefreshPicList
        {
            get { return _canRefreshPicList; }
            set
            {
                if (_canRefreshPicList == value)
                    return;
                _canRefreshPicList = value;
                NotifyOfPropertyChange(() => CanRefreshPicList);
            }
        }

        public void RefreshPicList()
        {
            LoadPictures();
        }

        private bool IsContained(int id)
        {
            return _picstoryList.Any(item => id == item.Id);
        }

        protected override void OnActivate()
        {
            _events.Subscribe(this);
            base.OnActivate();
        }

        protected override void OnDeactivate(bool close)
        {
            NaviSelectedIndex = -1;
            SelectedItem = null;
            _events.Unsubscribe(this);
            base.OnDeactivate(close);
        }

        public void NavigateToAboutUsPage()
        {
            _navigationService.UriFor<AboutUsViewModel>()
                .Navigate();
        }

    }
}